/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 19, 2012  5:08:23 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.outbound
 * File Name : FiApinvoicerentOutbService.java
 * TODO
 */
package sap.business.fi.outbound;

import java.util.ArrayList;
import java.util.List;

import jpa.entitys.synchro.staging.FiApinvoiceOutb;
import jpa.entitys.synchro.staging.FiApinvoicerentOutb;
import jpa.entitys.synchro.staging.FiArcnrentOutb;
import jpa.entitys.synchro.staging.FiArinvrentOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.FiApinvoiceOutbServices;
import jpa.service.synchro.staging.FiApinvoicerentOutbServices;

import org.apache.log4j.Logger;

import promis.utility.CommonService;

import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;

/**
 * @author chatree
 *
 */
public class FiApinvoicerentOutbService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(FiApinvoicerentOutbService.class);
	private FiApinvoicerentOutbServices fiApinvoicerentOutbServ; 

	/**
	 * 
	 */
	public FiApinvoicerentOutbService() {
		// TODO Auto-generated constructor stub
		try {
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
		} catch (Exception e) {
			log.error(e);
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {
				FiApinvoicerentOutb model = (FiApinvoicerentOutb)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				jcoTable.setValue("INTERFACE_NO", "FI-T1-030");
				jcoTable.setValue("BUKRS", model.getSapCompanyCode());
				jcoTable.setValue("BLDAT", model.getVoucherDate());
				jcoTable.setValue("BUDAT", model.getVoucherDate());
				jcoTable.setValue("WAERS", model.getCurrency());
				jcoTable.setValue("KURSF", model.getExchangeRate());
				jcoTable.setValue("XBLNR", model.getRefInvNo());
				jcoTable.setValue("BKTXT", model.getNarration());
				jcoTable.setValue("HKONT", model.getSupplierCode());
				
				//Exclude Vat or Befor Vat
				jcoTable.setValue("EXCVAT", model.getAmountAdjusted());
				
				//Include Vat
				//Add 2012-09-28 Pon,Pa Account, Nu, Archi ITOne
				jcoTable.setValue("INCVAT", model.getNetAmountAdjusted());
				
				//Add 2012-09-28 Pon,Pa Account, Nu, Archi ITOne
				jcoTable.setValue("REF_TAX_DOCUMENT", model.getRefTaxDocument());
				
				jcoTable.setValue("ZFBDT", model.getVoucherDate());
				jcoTable.setValue("ZUONR", model.getDocumentNo());
				//jcoTable.setValue("SGTXT", model.getRefContractNo());
				jcoTable.setValue("CHARGE_CODE", model.getChargeCode());
				jcoTable.setValue("PLANT_CODE", model.getSapPlantCode());
				jcoTable.setValue("PROMIS_UNIT_CODE", model.getUnitNumber());
				
				if(!CommonService.IsNull(model.getRefContractNo()))
					jcoTable.setValue("SGTXT", CommonService.IsNullRString(model.getUnitNumber())+","+ CommonService.IsNullRString(model.getRefContractNo()));
				else
					jcoTable.setValue("SGTXT", CommonService.IsNullRString(model.getUnitNumber()));
				
				jcoTable.setValue("STATUS", model.getStatus());
	        }
		}
		super.SynchroToSap(jcoFunction, jcoTable, value_list);
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		List<FiApinvoicerentOutb> lst = new ArrayList<FiApinvoicerentOutb>();
			if(!jcoTable_return.isEmpty()){
				log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
				for(int i = 0; i < jcoTable_return.getNumRows(); i++)
				{
					jcoTable_return.setRow(i);			
					FiApinvoicerentOutb model = fiApinvoicerentOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
					log.info(CommonJCOReturn.toString(jcoTable_return));
					
					if(model != null){
						
						model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
						model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
						model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
						model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
						model.setIsactive("Y");
						model.setIssync("Y");
						lst.add(model);
					}
				}
			}else
				log.info(CommonJCOReturn.toString(jcoTable_return));
			
			fiApinvoicerentOutbServ.Updated(lst);
			
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<FiApinvoicerentOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<FiApinvoicerentOutb> newlst = new ArrayList<FiApinvoicerentOutb>();
				for(FiApinvoicerentOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new FiApinvoicerentOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendToSAP(List<FiApinvoicerentOutb> value_list) throws Exception
	{
		try{
			
			if(!CommonService.IsNull(value_list))
			{
				this.sap_bapi = "ZIN_FIAP_INVOICE_RT";
				this.sap_table = "ACCT_DATA";
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
				fiApinvoicerentOutbServ = new FiApinvoicerentOutbServices(this.emSynchro);

				//Get SAP BAPI function 
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);			
				
				//List<FiApinvoicerentOutb> value_list = fiApinvoicerentOutbServ.findIsSync("N");
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
			}
			
		}catch(Exception e){
			UpdateStagingWhenError(value_list, e);
			log.error(e);
			throw e;			
		}
		
	}
	
	private void Start() throws Exception
	{
		this.sap_bapi = "ZTIN_AP_STAG_IRT";
		this.sap_table = "ACCT_DATA";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();

		//Get SAP BAPI function 
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		fiApinvoicerentOutbServ = new FiApinvoicerentOutbServices(this.emSynchro);
		List<FiApinvoicerentOutb> value_list = fiApinvoicerentOutbServ.findIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		try{
//			
//			FiApinvoicerentOutbService obj = new FiApinvoicerentOutbService();
//			obj.Start();
//			
//		}catch(Exception ex)
//		{
//			ex.printStackTrace();
//			log.error(ex);
//		}
//	}

}
